package epidemic

import (
	"context"
	"encoding/json"
	"errors"
	"gitee.com/baal1990/epidemic/utils/prepare"
	"go.uber.org/zap"
	"strconv"
	"strings"
	"time"

	"gitee.com/baal1990/epidemic/global"
	"gitee.com/baal1990/epidemic/model/epidemic"
	epidemicReq "gitee.com/baal1990/epidemic/model/epidemic/request"
	"github.com/xuri/excelize/v2"
)

type EpidemicRelatedStaffService struct {
}

// CreateEpidemicRelatedStaff 创建EpidemicRelatedStaff记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) CreateEpidemicRelatedStaff(epidemicRelatedStaff epidemic.EpidemicRelatedStaff) (err error) {
	err = global.GVA_DB.Create(&epidemicRelatedStaff).Error
	return err
}

// DeleteEpidemicRelatedStaff 删除EpidemicRelatedStaff记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) DeleteEpidemicRelatedStaff(id string) (err error) {
	// 创建db
	db := global.GVA_DB.Model(&epidemic.EpidemicRelatedStaff{}).Where("id=?", id)
	// 查找手机号
	var mobile string
	if err = db.Select("mobile").
		Find(&mobile).Error; err != nil {
		return
	}
	// 同步删除history
	service := EpidemicRelatedStaffHistoryService{}
	service.SyncHistory(mobile, global.SYNC_MODE_DELETE)
	// 删除
	if err = db.Unscoped().Delete(&epidemic.EpidemicRelatedStaff{}).Error; err != nil {
		return
	}
	return
}

// UpdateEpidemicRelatedStaff 更新EpidemicRelatedStaff记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) UpdateEpidemicRelatedStaff(epidemicRelatedStaff epidemic.EpidemicRelatedStaff) (err error) {
	err = global.GVA_DB.Save(&epidemicRelatedStaff).Error
	return err
}

// GetEpidemicRelatedStaff 根据id获取EpidemicRelatedStaff记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) GetEpidemicRelatedStaff(id uint) (epidemicRelatedStaff epidemic.EpidemicRelatedStaff, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&epidemicRelatedStaff).Error
	return
}

// GetEpidemicRelatedStaffInfoList 分页获取EpidemicRelatedStaff记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) GetEpidemicRelatedStaffInfoList(info epidemicReq.EpidemicRelatedStaffSearch, user epidemic.EpidemicUser) (list []epidemic.EpidemicRelatedStaff, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&epidemic.EpidemicRelatedStaff{})
	if user.Role != global.DICT_ROLES_SUPER {
		db = db.Where("company=? and department in ?", user.Company, prepare.Department(user.Department))
	}
	var epidemicRelatedStaffs []epidemic.EpidemicRelatedStaff
	// 如果有条件搜索 下方会自动创建搜索语句
	if len(info.Name) > 0 {
		db = db.Where("AES_DECRYPT(FROM_BASE64(`name`),'"+global.ENCRYPTKEY_AES+"') like ?", "%"+info.Name+"%")
	}
	if len(info.Company) > 0 {
		db = db.Where("company = ?", info.Company)
	}
	if len(info.Department) > 0 {
		db = db.Where("department = ?", info.Department)
	}
	if len(info.Organization) > 0 {
		db = db.Where("organization = ?", info.Organization)
	}
	if len(info.Location) > 0 {
		db = db.Where("location = ?", info.Location)
	}
	if len(info.IsolationType) > 0 {
		db = db.Where("isolation_type = ?", info.IsolationType)
	}
	if len(info.HomeBeginDateStart) > 0 && len(info.HomeBeginDateEnd) > 0 {
		db = db.Where("home_begin_date >= ? and home_begin_date <= ?", info.HomeBeginDateStart, info.HomeBeginDateEnd)
	}
	if len(info.CompanyOaDateStart) > 0 && len(info.CompanyOaDateEnd) > 0 {
		db = db.Where("company_oa_date >= ? and company_oa_date <= ?", info.CompanyOaDateStart, info.CompanyOaDateEnd)
	}
	if len(info.ReturnDateStart) > 0 && len(info.ReturnDateEnd) > 0 {
		db = db.Where("return_date >= ? and return_date <= ?", info.ReturnDateStart, info.ReturnDateEnd)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	if err = db.Limit(limit).Offset(offset).Order("id desc").Find(&epidemicRelatedStaffs).Error; err != nil {
		global.GVA_LOG.Error("加密失败!", zap.Error(err))
		return
	}
	for i := 0; i < len(epidemicRelatedStaffs); i++ {
		NucleicAcidRecord := ""
		TemperatureRecord := ""
		epidemicRelatedStaffs[i].Details = "居住地址：" + epidemicRelatedStaffs[i].RegionName + epidemicRelatedStaffs[i].ResidentialAddress + "\r\n所属社区：" + epidemicRelatedStaffs[i].Community + "\r\n社区电话：" + epidemicRelatedStaffs[i].CommunityTel
		epidemicRelatedStaffs[i].Details += "\r\n所属接到：" + epidemicRelatedStaffs[i].Street + "\r\n情况描述：" + epidemicRelatedStaffs[i].Description + "\r\n社区要求：" + epidemicRelatedStaffs[i].CommunityRequirements + "\r\n核酸记录："
		NucleicAcidRecord, err = marshalNucleicAcidRecord(epidemicRelatedStaffs[i].NucleicAcidRecord)
		if err != nil {
			global.GVA_LOG.Error("加密失败!", zap.Error(err))
		}
		epidemicRelatedStaffs[i].Details += NucleicAcidRecord + "\r\n体温记录："
		TemperatureRecord, err = marshalTemperatureRecord(epidemicRelatedStaffs[i].TemperatureRecord)
		if err != nil {
			global.GVA_LOG.Error("加密失败!", zap.Error(err))
		}
		epidemicRelatedStaffs[i].Details += TemperatureRecord
		// 处理加密字段
		epidemicRelatedStaffs[i].Name, err = global.AsymmetricCrypto.EncryptWithPrvKOutputBase64([]byte(epidemicRelatedStaffs[i].Name))
		if err != nil {
			global.GVA_LOG.Error("加密失败!", zap.Error(err))
		}
		epidemicRelatedStaffs[i].Mobile, err = global.AsymmetricCrypto.EncryptWithPrvKOutputBase64([]byte(epidemicRelatedStaffs[i].Mobile))
		if err != nil {
			global.GVA_LOG.Error("加密失败!", zap.Error(err))
		}
		epidemicRelatedStaffs[i].Region, err = global.AsymmetricCrypto.EncryptWithPrvKOutputBase64([]byte(epidemicRelatedStaffs[i].Region))
		if err != nil {
			global.GVA_LOG.Error("加密失败!", zap.Error(err))
		}
		epidemicRelatedStaffs[i].RegionName, err = global.AsymmetricCrypto.EncryptWithPrvKOutputBase64([]byte(epidemicRelatedStaffs[i].RegionName))
		if err != nil {
			global.GVA_LOG.Error("加密失败!", zap.Error(err))
		}
		epidemicRelatedStaffs[i].ResidentialAddress, err = global.AsymmetricCrypto.EncryptWithPrvKOutputBase64([]byte(epidemicRelatedStaffs[i].ResidentialAddress))
		if err != nil {
			global.GVA_LOG.Error("加密失败!", zap.Error(err))
		}
		epidemicRelatedStaffs[i].Details, err = global.AsymmetricCrypto.EncryptWithPrvKOutputBase64([]byte(epidemicRelatedStaffs[i].Details))
		if err != nil {
			global.GVA_LOG.Error("加密失败!", zap.Error(err))
		}
	}
	return epidemicRelatedStaffs, total, err
}

// GetEpidemicRelatedStaffInfoList 分页获取EpidemicRelatedStaff记录
// Author [piexlmax](https://github.com/piexlmax)
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) GetEpidemicRelatedStaffInfoListForImport() (list []epidemic.EpidemicRelatedStaff, err error) {
	// 创建db
	db := global.GVA_DB.Model(&epidemic.EpidemicRelatedStaff{})
	if err = db.Find(&list).Error; err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		return
	}
	return
}

func (epidemicRelatedStaffService *EpidemicRelatedStaffService) GetFillingProcess(user epidemic.EpidemicUser, name string) (filling int64, err error) {
	// 创建db
	db := global.GVA_DB.Model(&epidemic.EpidemicRelatedStaff{})
	if user.Role != global.DICT_ROLES_SUPER {
		db = db.Where("company=? and department in ?", user.Company, prepare.Department(user.Department))
	}
	if len(name) > 0 {
		db = db.Where("AES_DECRYPT(FROM_BASE64(`name`),'"+global.ENCRYPTKEY_AES+"') like ?", "%"+name+"%")
	}
	db = db.Where("report_date>=CURRENT_DATE()")
	err = db.Count(&filling).Error
	if err != nil {
		return
	}
	return filling, err
}

func (epidemicRelatedStaffService *EpidemicRelatedStaffService) GetAutoNotifyStatus(user epidemic.EpidemicUser) (status string, err error) {
	// 创建db
	db := global.GVA_DB.Model(&epidemic.EpidemicRelatedStaff{})
	if user.Role != global.DICT_ROLES_SUPER {
		db = db.Where("company=? and department in ?", user.Company, prepare.Department(user.Department))
	}
	result := global.GVA_REDIS.Get(context.Background(), global.REDIS_KEY_AUTO_NOTIFY_STATUS)
	if result.Val() == global.AUTO_NOTIFY_START {
		status = result.Val()
	} else {
		status = global.AUTO_NOTIFY_STOP
	}
	global.GVA_LOG.Info("auto-notify status:", zap.Any("any", status))
	return
}

// 用户侧
// 获取涉疫员工信息
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) GetEpidemicRelatedStaffInfoUserSide(mobile string) (info epidemic.EpidemicRelatedStaff, err error) {
	// 创建db
	db := global.GVA_DB.Model(&epidemic.EpidemicRelatedStaff{})
	// 获取信息
	err = db.Where("mobile = ?", mobile).First(&info).Error
	return info, err
}

// 用户侧
// 登记涉疫员工信息
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) EpidemicRelatedStaffCheckinUserSide(req epidemicReq.EpidemicRelatedStaffCheckinUserSide) (err error) {
	// 创建db
	homeBegin, err := time.ParseInLocation("2006-01-02", req.HomeBeginDate, time.Local)
	if err != nil {
		return err
	}
	staff := epidemic.EpidemicRelatedStaff{
		Name:                  req.Name,
		Mobile:                req.Mobile,
		Company:               req.Company,
		Department:            req.Department,
		Organization:          req.Organization,
		Location:              req.Location,
		AppletReport:          req.AppletReport,
		IsolationType:         req.IsolationType,
		Region:                req.Region,
		RegionName:            req.RegionName,
		ResidentialAddress:    req.ResidentialAddress,
		Community:             req.Community,
		CommunityTel:          req.CommunityTel,
		Street:                req.Street,
		Description:           req.Description,
		CommunityRequirements: req.CommunityRequirements,
		HomeBeginDate:         &homeBegin,
	}

	now := time.Now()
	staff.ReportDate = &now
	staff.ReportedBy = req.Name
	var count int64 = 0
	if err = global.GVA_DB.Table("epidemic_related_staff").Where("mobile=?", req.Mobile).Count(&count).Error; err != nil {
		return err
	}
	service := EpidemicRelatedStaffHistoryService{}
	if count == 0 {
		err = global.GVA_DB.Save(&staff).Error
		service.SyncHistory(req.Mobile, global.SYNC_MODE_ADD)
	} else {
		err = global.GVA_DB.Where("mobile=?", req.Mobile).Updates(&staff).Error
		service.SyncHistory(req.Mobile, global.SYNC_MODE_UPDATE)
	}
	return
}

// 用户侧
// 登记健康信息
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) EpidemicRelatedStaffInfoUserSide(mobile, name string, req epidemicReq.HealthCheckinUserSide) (err error) {
	// 创建db
	db := global.GVA_DB
	// 获取信息
	info := epidemic.EpidemicRelatedStaff{}
	if err = db.Where("mobile = ?", mobile).First(&info).Error; err != nil {
		return
	}
	// 记录体温
	if info.TemperatureRecord, err = updateTemperatureRecord(req, info); err != nil {
		return err
	}
	// 记录核酸
	none, err := GetValueByKeyAndName("aicd_test_status", "无")
	if err != nil {
		return
	}
	if req.DetectionTime != "" && req.CovidTesting != none {
		if info.NucleicAcidRecord, err = updateCovidTesting(req, info); err != nil {
			return err
		}
	}
	// 更新调表日期和填表人
	info.ReportedBy = name
	now := time.Now()
	info.ReportDate = &now
	err = db.Where("mobile=?", mobile).Updates(&info).Error
	service := EpidemicRelatedStaffHistoryService{}
	service.SyncHistory(req.Mobile, global.SYNC_MODE_UPDATE)
	return
}

// 更新体温记录
func updateTemperatureRecord(req epidemicReq.HealthCheckinUserSide, info epidemic.EpidemicRelatedStaff) (string, error) {
	var records epidemic.TemperatureRecords
	if info.TemperatureRecord != "" {
		if err := json.Unmarshal([]byte(info.TemperatureRecord), &records); err != nil {
			return "", err
		}
	}
	nowDate := time.Now().Format("2006-01-02")
	// 从未登记
	if len(records.Records) == 0 {
		records.Records = append(records.Records, genTemperatureRecordByDate(nowDate, req))
	} else {
		// 找到最后一个日期
		last := len(records.Records) - 1
		// 日期不同，直接追加日期记录
		if records.Records[last].Date != nowDate {
			records.Records = append(records.Records, genTemperatureRecordByDate(nowDate, req))
		} else {
			// 日期相同，更新
			records.Records[last] = genTemperatureRecordByDate(nowDate, req)
		}
	}
	result, err := json.Marshal(&records)
	if err != nil {
		return "", err
	}
	return string(result), nil
}

// 根据日期生成体温记录
func genTemperatureRecordByDate(nowDate string, req epidemicReq.HealthCheckinUserSide) epidemic.TemperatureByDate {
	t := epidemic.TemperatureByDate{
		Date: nowDate,
	}
	morning, err := GetValueByKeyAndName("interval", "上午")
	if err != nil {
		morning = "1"
	}
	afternoon, err := GetValueByKeyAndName("interval", "下午")
	if err != nil {
		afternoon = "2"
	}
	t.Temperatures = append(t.Temperatures, epidemic.Temperature{
		Interval:    morning,
		Temperature: req.TemperatureMorning,
	}, epidemic.Temperature{
		Interval:    afternoon,
		Temperature: req.TemperatureAfternoon,
	})
	return t
}

// 更新核酸记录
func updateCovidTesting(req epidemicReq.HealthCheckinUserSide, info epidemic.EpidemicRelatedStaff) (string, error) {
	var records epidemic.CovidTestingRecords
	if info.NucleicAcidRecord != "" {
		if err := json.Unmarshal([]byte(info.NucleicAcidRecord), &records); err != nil {
			return "", err
		}
	}
	nowDate := req.DetectionTime
	// 从未登记
	if len(records.Records) == 0 {
		records.Records = append(records.Records, genCovidTestingByDate(nowDate, req))
	} else {
		// 找到最后一个日期的记录
		last := len(records.Records) - 1
		// 日期不一样，直接追加
		if records.Records[last].Date != nowDate {
			seen := false
			// 如果已经上报过的，更新历史记录
			for i := 0; i < len(records.Records); i++ {
				if records.Records[i].Date == nowDate {
					seen = true
					records.Records[i].Result = req.CovidTesting
					break
				}
			}
			// 新日期，追加
			if !seen {
				records.Records = append(records.Records, genCovidTestingByDate(nowDate, req))
			}
		} else {
			// 日期一样更新，更新最后一个
			records.Records[last].Result = req.CovidTesting
		}
	}
	result, err := json.Marshal(&records)
	if err != nil {
		return "", err
	}
	return string(result), nil
}

// 根据日期生成核酸记录
func genCovidTestingByDate(nowDate string, req epidemicReq.HealthCheckinUserSide) epidemic.CovidTestingByDate {
	return epidemic.CovidTestingByDate{
		Date:   nowDate,
		Result: req.CovidTesting,
	}
}

// 导出全部
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) ExportAll(user epidemic.EpidemicUser) (filename string, err error) {
	// 创建db
	db := global.GVA_DB.Model(&epidemic.EpidemicRelatedStaff{})
	// 获取信息
	if user.Role != global.DICT_ROLES_SUPER {
		db = db.Where("department in ? and company=?", prepare.Department(user.Department), user.Company)
	} else {
		db = db.Where("company=?", user.Company)
	}
	var info []epidemic.EpidemicRelatedStaff
	if err = db.Find(&info).Error; err != nil {
		return
	}

	return epidemicRelatedStaffService.GenExcel(info)
}

// 编辑涉疫人员信息
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) SaveEpidemicRelatedStaff(name string, req epidemicReq.EpidemicRelatedStaffSet) (err error) {
	// 去掉无效记录
	void := ""
	void, err = GetValueByKeyAndName("aicd_test_status", "无")
	if err != nil {
		return
	}
	covidTestingRecords := epidemic.CovidTestingRecords{}
	if len(req.NucleicAcidRecord) > 0 {
		if err = json.Unmarshal([]byte(req.NucleicAcidRecord), &covidTestingRecords); err != nil {
			return
		}
		for i := 0; i < len(covidTestingRecords.Records); i++ {
			if covidTestingRecords.Records[i].Result == void || covidTestingRecords.Records[i].Date == "" {
				covidTestingRecords.Records = append(covidTestingRecords.Records[:i], covidTestingRecords.Records[i+1:]...)
				i--
			}
		}
	}
	temperatureRecords := epidemic.TemperatureRecords{}
	if len(req.TemperatureRecord) > 0 {
		if err = json.Unmarshal([]byte(req.TemperatureRecord), &temperatureRecords); err != nil {
			return
		}
		for i := 0; i < len(temperatureRecords.Records); i++ {
			if temperatureRecords.Records[i].Date == "" {
				temperatureRecords.Records = append(temperatureRecords.Records[:i], temperatureRecords.Records[i+1:]...)
				i--
			}
		}
	}
	tmp, err := json.Marshal(covidTestingRecords)
	if err != nil {
		return
	}
	req.NucleicAcidRecord = string(tmp)
	tmp, err = json.Marshal(temperatureRecords)
	if err != nil {
		return
	}
	req.TemperatureRecord = string(tmp)

	// 创建db
	db := global.GVA_DB
	info := epidemic.EpidemicRelatedStaff{
		Mobile:                req.Mobile,
		Name:                  req.Name,
		Company:               req.Company,
		Department:            req.Department,
		Organization:          req.Organization,
		Location:              req.Location,
		AppletReport:          req.AppletReport,
		IsolationType:         req.IsolationType,
		Region:                req.Region,
		RegionName:            req.RegionName,
		ResidentialAddress:    req.ResidentialAddress,
		Community:             req.Community,
		CommunityTel:          req.CommunityTel,
		Street:                req.Street,
		Description:           req.Description,
		CommunityRequirements: req.CommunityRequirements,
		NucleicAcidRecord:     req.NucleicAcidRecord,
		TemperatureRecord:     req.TemperatureRecord,
		ReportedBy:            name,
	}
	if req.HomeBeginDate != "" {
		t, err := time.ParseInLocation("2006-01-02", req.HomeBeginDate, time.Local)
		if err != nil {
			return err
		}
		info.HomeBeginDate = &t
	}
	if req.CompanyOaDate != "" {
		t, err := time.ParseInLocation("2006-01-02", req.CompanyOaDate, time.Local)
		if err != nil {
			return err
		}
		info.CompanyOaDate = &t
	}
	if req.ReturnDate != "" {
		t, err := time.ParseInLocation("2006-01-02", req.ReturnDate, time.Local)
		if err != nil {
			return err
		}
		info.ReturnDate = &t
	}
	now := time.Now()
	info.ReportDate = &now
	service := EpidemicRelatedStaffHistoryService{}

	if req.Id != 0 {
		info.ID = uint(req.Id)
		err = db.Where("id=?", info.ID).Select("*").Omit("created_at").Updates(&info).Error
		service.SyncHistory(info.Mobile, global.SYNC_MODE_UPDATE)
	} else {
		err = db.Save(&info).Error
		service.SyncHistory(info.Mobile, global.SYNC_MODE_ADD)
	}
	return
}

// 新增（import)
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) SaveEpidemicRelatedStaffForImport(info epidemic.EpidemicRelatedStaff) (err error) {
	// 创建db
	db := global.GVA_DB
	if info.ID != 0 {
		err = db.Where("id=?", info.ID).Select("*").Omit("created_at").Updates(&info).Error
	} else {
		err = db.Save(&info).Error
	}
	return
}

// GenExcel 生成excel
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) GenExcel(info []epidemic.EpidemicRelatedStaff) (string, error) {
	f := excelize.NewFile()
	// Create a new sheet.
	sheet := "Sheet1"
	index := f.NewSheet(sheet)
	// Set value of a cell.
	if err := epidemicRelatedStaffService.genExcelTittle(f, sheet); err != nil {
		return "", err
	}
	for i, e := range info {
		line := i + 2
		id := i + 1
		if err := epidemicRelatedStaffService.genExcelLine(e, f, sheet, line, id); err != nil {
			return "", err
		}
	}
	// Set active sheet of the workbook.
	f.SetActiveSheet(index)
	// Save spreadsheet by the given path.
	nowDate := time.Now().Format("2006-01-02")
	fileName := global.GVA_CONFIG.System.ExportFileDir + "涉疫人员" + nowDate + ".xlsx"
	if err := f.SaveAs(fileName); err != nil {
		return "", err
	}
	return fileName, nil
}

// 生成标头
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) genExcelTittle(f *excelize.File, sheet string) error {
	var Tittle = []string{
		"序号",
		"姓名",
		"公司",
		"部门",
		"编制",
		"小程序上传\n（含居家证明）",
		"工作地点",
		"居家情况分类",
		"具体情况",
		"居家日期",
		"返岗日期",
		"公司OA提交",
		"更新填表日期",
		"填表人",
	}
	for i := 0; i < len(Tittle); i++ {
		axis := string(rune(65 + i))
		value := Tittle[i]
		if err := f.SetCellValue(sheet, axis+strconv.Itoa(1), value); err != nil {
			return err
		}
	}
	return nil
}

func (epidemicRelatedStaffService *EpidemicRelatedStaffService) genExcelLine(info epidemic.EpidemicRelatedStaff, f *excelize.File, sheet string, line, id int) error {
	i := 0
	if err := setCellValue(f, &i, id, sheet, line); err != nil {
		return err
	}
	if err := setCellValue(f, &i, info.Name, sheet, line); err != nil {
		return err
	}
	Company, _ := GetNameByKeyAndValue("company", info.Company)
	if err := setCellValue(f, &i, Company, sheet, line); err != nil {
		return err
	}
	departmentSlice := strings.Split(info.Department, ",")
	Department := ""
	for i, e := range departmentSlice {
		tmp, _ := GetNameByKeyAndValue("department", e)
		Department += tmp
		if i+1 != len(departmentSlice) {
			Department += ","
		}
	}
	if err := setCellValue(f, &i, Department, sheet, line); err != nil {
		return err
	}
	Organization, _ := GetNameByKeyAndValue("organization", info.Organization)
	if err := setCellValue(f, &i, Organization, sheet, line); err != nil {
		return err
	}
	AppletReport, _ := GetNameByKeyAndValue("investigation_isupload", info.AppletReport)
	if err := setCellValue(f, &i, AppletReport, sheet, line); err != nil {
		return err
	}
	Location, _ := GetNameByKeyAndValue("workcity", info.Location)
	if err := setCellValue(f, &i, Location, sheet, line); err != nil {
		return err
	}
	IsolationType, _ := GetNameByKeyAndValue("investigation_type", info.IsolationType)
	if err := setCellValue(f, &i, IsolationType, sheet, line); err != nil {
		return err
	}

	tmp := "居住地址：" + info.RegionName + info.ResidentialAddress + "\r\n所属社区：" + info.Community + "\r\n社区电话：" + info.CommunityTel + "\r\n所属接到：" + info.Street
	tmp += "\r\n情况描述：" + info.Description + "\r\n社区要求：" + info.CommunityRequirements + "\r\n核酸记录："
	NucleicAcidRecord, err := marshalNucleicAcidRecord(info.NucleicAcidRecord)
	if err != nil {
		return err
	}
	tmp += NucleicAcidRecord + "\r\n体温记录："
	TemperatureRecord, err := marshalTemperatureRecord(info.TemperatureRecord)
	if err != nil {
		return err
	}
	tmp += TemperatureRecord
	if err := setCellValue(f, &i, tmp, sheet, line); err != nil {
		return err
	}
	if info.HomeBeginDate != nil {
		if err := setCellValue(f, &i, info.HomeBeginDate.Format("2006/01/02"), sheet, line); err != nil {
			return err
		}
	} else {
		if err := setCellValue(f, &i, "", sheet, line); err != nil {
			return err
		}
	}
	if info.ReturnDate != nil {
		if err := setCellValue(f, &i, info.ReturnDate.Format("2006/01/02"), sheet, line); err != nil {
			return err
		}
	} else {
		if err := setCellValue(f, &i, "", sheet, line); err != nil {
			return err
		}
	}
	if info.CompanyOaDate != nil {
		if err := setCellValue(f, &i, info.CompanyOaDate.Format("2006/01/02"), sheet, line); err != nil {
			return err
		}
	} else {
		if err := setCellValue(f, &i, "", sheet, line); err != nil {
			return err
		}
	}
	if info.ReportDate != nil {
		if err := setCellValue(f, &i, info.ReportDate.Format("2006/01/02"), sheet, line); err != nil {
			return err
		}
	} else {
		if err := setCellValue(f, &i, "", sheet, line); err != nil {
			return err
		}
	}
	if err := setCellValue(f, &i, info.ReportedBy, sheet, line); err != nil {
		return err
	}
	return nil
}

// 写入单元格
func setCellValue(f *excelize.File, i *int, value interface{}, sheet string, line int) error {
	axis := string(rune(65+*i)) + strconv.Itoa(line)
	if err := f.SetCellValue(sheet, axis, value); err != nil {
		return err
	}
	*i++
	return nil
}

// 序列化体温记录
func marshalTemperatureRecord(j string) (string, error) {
	var records epidemic.TemperatureRecords
	if j == "" {
		// 空就空着，不算错误
		return "", nil
	}
	if err := json.Unmarshal([]byte(j), &records); err != nil {
		return "", err
	}
	result := ""
	for j, e := range records.Records {
		t, err := time.ParseInLocation("2006-01-02", e.Date, time.Local)
		if err != nil {
			return "", err
		}
		result += t.Format("1月2日")
		for i, e2 := range e.Temperatures {
			interval, _ := GetNameByKeyAndValue("interval", e2.Interval)
			result += interval + e2.Temperature
			if i+1 != len(e.Temperatures) {
				result += "、"
			}
		}
		if j+1 != len(records.Records) {
			result += ","
		}
	}
	return result, nil
}

// 序列化核酸记录
func marshalNucleicAcidRecord(j string) (string, error) {
	var records epidemic.CovidTestingRecords
	if j == "" {
		// 空就空着，不算错误
		return "", nil
	}
	if err := json.Unmarshal([]byte(j), &records); err != nil {
		return "", err
	}
	result := ""
	for i, e := range records.Records {
		t, err := time.ParseInLocation("2006-01-02", e.Date, time.Local)
		if err != nil {
			return "", err
		}
		result += t.Format("1月2日")
		nucleicAcidResult, _ := GetNameByKeyAndValue("aicd_test_status", e.Result)
		result += nucleicAcidResult
		if i+1 != len(records.Records) {
			result += ","
		}
	}
	return result, nil
}

// 新增（import)
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) AutoNotify(req epidemicReq.AutoNotify) (err error) {
	if req.Operation == global.AUTO_NOTIFY_START {
		global.GVA_Timer.StartTask(global.CRONTAB_NOTIFY)
	} else if req.Operation == global.AUTO_NOTIFY_STOP {
		global.GVA_Timer.StopTask(global.CRONTAB_NOTIFY)
	} else {
		err = errors.New("参数错误")
	}
	if err == nil {
		// 记录状态
		global.GVA_REDIS.Set(context.Background(), global.REDIS_KEY_AUTO_NOTIFY_STATUS, req.Operation, 0)
	}
	return
}

// Return 返岗
func (epidemicRelatedStaffService *EpidemicRelatedStaffService) Return(req epidemicReq.EpidemicRelatedStaffReturn) (err error) {
	// 同步history
	t, err := time.ParseInLocation("2006-01-02", req.ReturnDate, time.Local)
	if err != nil {
		return err
	}
	service := EpidemicRelatedStaffHistoryService{}
	service.SyncHistoryReturn(req.Id, &t)
	// 删除
	if err = global.GVA_DB.Model(&epidemic.EpidemicRelatedStaff{}).
		Where("id=?", req.Id).
		Unscoped().
		Delete(&epidemic.EpidemicRelatedStaff{}).Error; err != nil {
		return
	}
	return
}
